package cn.cloudtogo.common.atomapi;

import cn.cloudtogo.common.Assert;
import cn.cloudtogo.common.GendbException;
import cn.cloudtogo.common.atomapi.token.ApiResource;
import cn.cloudtogo.common.util.StringHelper;

/**
 * @author yaolianhua789@gmail.com
 **/
public final class AtomApiHelper {

    private AtomApiHelper() {
    }

    public static String generateApiKey(String uuid, String table, ApiMethodModel methodModel) {
        return StringHelper.encode("|", new String[]{uuid, table, methodModel.getNotes()});
    }

    public static ApiResource generateApiResource(ApiMethodModel apiMethod, ApiResource.ResourceLevel level) {
        String[] args = StringHelper.decode(apiMethod.getApiKey()).split("\\|");
        Assert.state(args.length == 3, () -> "api key invalid");
        String uuid = args[0];
        String table = args[1];
        String operation = args[2];
        switch (level) {
            case SCHEMA:
                return ApiResource.of(apiMethod.getMethod(), String.format("/api/%s/*", uuid));
            case TABLE:
                return ApiResource.of(apiMethod.getMethod(), String.format("/api/%s/%s/*", uuid, table));
            default:
                throw new GendbException(String.format("Unsupported Api resource level [%s]", level));
        }
    }
}
